//
//  HttpHelper.m
//  创乐付
//
//  Created by wyx on 2017/5/4.
//  Copyright © 2017年 wyx. All rights reserved.
//

#import "HttpHelper.h"
#import "AFNetworking.h"

@implementation HttpHelper

#pragma mark - 创建请求者


+ (void)GET:(NSString *)URLString
 parameters:(id)parameters
    success:(void (^)(id responseObject))success
    failure:(void (^)(NSError *error))failure{
    // get请求也可以直接将参数放在字典里，AFN会自己讲参数拼接在url的后面，不需要自己凭借
   AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    // 声明获取到的数据格式
    manager.responseSerializer = [AFHTTPResponseSerializer serializer]; // AFN不会解析,数据是data，需要自己解析
    NSString * jsonStr = [NSString dictionaryToJson:parameters];

    
//    NSLog(@"qqqqq%@ %@",parameters, jsonStr);
    [manager GET:URLString parameters:jsonStr progress:^(NSProgress * _Nonnull downloadProgress) {
        // 这里可以获取到目前数据请求的进度
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        // 请求成功
        if(responseObject){
            NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
            success(dict);
        } else {
            NSString * str = @"暂无数据";
            success(str);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        // 请求失败
        failure(error);
    }];
}

+ (void)Post:(NSString *)URLString
  parameters:(id)parameters
     success:(void (^)(id responseObject))success
     failure:(void (^)(NSError *error))failure{
    // 创建请求管理者
    AFHTTPSessionManager *session = [AFHTTPSessionManager manager];
    // 不加上这句话，会报“Request failed: unacceptable content-type: text/plain”错误，因为我们要获取text/plain类型数据
    
    session.responseSerializer = [AFHTTPResponseSerializer serializer]; // 声明请求的数据类型是json格式
    session.responseSerializer.acceptableContentTypes = nil;
    session.requestSerializer = [AFHTTPRequestSerializer serializer]; // 声明返回的结果是json格式
    NSString * allUrl = [NSString stringWithFormat:@"%@/%@",kBaseURL,URLString];
    NSString * utf = [allUrl stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    NSString * jsonStr = [NSString dictionaryToJson:parameters];
    NSDictionary * parametDict = [NSDictionary dictionaryWithObject:jsonStr forKey:@"jsonStr"];
    MyLog(@"%@ %@",utf,parametDict);
    [session POST:utf parameters:parametDict progress:^(NSProgress * _Nonnull uploadProgress) {
        // 这里可以获取到目前的数据请求的进度
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if (success) {
            // 请求成功，解析数据
            NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers | NSJSONReadingMutableLeaves error:nil];
            if (![HttpHelper isBlankDictionary:dic]) {
                MyLog(@"requestSucessDic---%@",dic);
                success(dic);
            }else
            {
                MyLog(@"nullDic---%@",dic);
            }
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (failure) {
            failure(error);
           MyLog(@"error---%@",error);
        }
    }];
}
+ (void)FormPost:(NSString *)URLString   parameters:(id)parameters imageData:(NSData *)imageDate fileName:(NSString *)fileName success:(void (^)(id responseObject))success  failure:(void (^)(NSError *error))failure{
    AFHTTPSessionManager *session = [AFHTTPSessionManager manager];
    session.requestSerializer.timeoutInterval = 40;
    [session.requestSerializer setValue:@"multipart/form-data" forHTTPHeaderField:@"Content-Type"];
    session.responseSerializer = [AFHTTPResponseSerializer serializer];
    session.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json",  @"application/octet-stream",@"text/html", @"application/xml", @"image/jpeg", @"image/png", nil];
    NSString * allUrl = [NSString stringWithFormat:@"%@/%@",kBaseURL,URLString];
    NSString * utf = [allUrl stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    NSString * nowTimeStr = [NSString getCurrentTimes];
    NSString * finalFileName = [NSString stringWithFormat:@"%@%@.jpg",fileName,nowTimeStr];
    [session POST:utf parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        [formData appendPartWithFileData:imageDate name:fileName fileName:finalFileName mimeType:@"image/jpg"];
    } progress:^(NSProgress * _Nonnull uploadProgress) {
    
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if (success) {
            // 请求成功，解析数据
            NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers | NSJSONReadingMutableLeaves error:nil];
            MyLog(@"---dict%@",dic);
            success(dic);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (failure) {
            failure(error);
            MyLog(@"error---%@",error);
        }
    }];
}

+ (void)uploadFileFormPostWithImageData:(NSData *)imageDate fileName:(NSString *)fileName success:(void (^)(id responseObject))success  failure:(void (^)(NSError *error))failure{
    AFHTTPSessionManager *session = [AFHTTPSessionManager manager];
    session.requestSerializer.timeoutInterval = 40;
    [session.requestSerializer setValue:@"multipart/form-data" forHTTPHeaderField:@"Content-Type"];
    session.responseSerializer = [AFHTTPResponseSerializer serializer];
    session.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json",  @"application/octet-stream",@"text/html", @"application/xml", @"image/jpeg", @"image/png", nil];
    NSString * URLString = @"ycs/upLoad/upLoad.do";
    NSString * allUrl = [NSString stringWithFormat:@"%@/%@",kBaseURL,URLString];
    NSString * utf = [allUrl stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    NSString * nowTimeStr = [NSString getCurrentTimes];
    NSString * finalFileName = [NSString stringWithFormat:@"%@%@.jpg",fileName,nowTimeStr];
    NSDictionary * parameDic = [NSDictionary dictionary];
    parameDic =@{
                 @"picType":fileName //目录
                 };
    [session POST:utf parameters:parameDic constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        [formData appendPartWithFileData:imageDate name:@"files" fileName:finalFileName mimeType:@"image/jpg"];
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if (success) {
            // 请求成功，解析数据
            NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers | NSJSONReadingMutableLeaves error:nil];
            if (![HttpHelper isBlankDictionary:dic]) {
                success(dic);
            }else
            {
                MyLog(@"requestDic---%@",dic);
            }
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (failure) {
            failure(error);
            MyLog(@"error---%@",error);
        }
    }];
    
}

+ (BOOL)isBlankDictionary:(NSDictionary *)dic {
    if (!dic) {
        return YES;
    }
    if ([dic isKindOfClass:[NSNull class]]) {
        return YES;
    }
    if (![dic isKindOfClass:[NSDictionary class]]) {
        return YES;
    }
    if (!dic.count) {
        return YES;
    }
    if (dic == nil) {
        return YES;
    }
    if (dic == NULL) {
        return YES;
    }
    return NO;
}




@end
